#include "stack.h"  
ST * createStack(){
    ST *stack   = (ST*)malloc(sizeof(ST));
    ERROR_CHECK(NULL,stack,"malloc stack");
    stack->data = (type*)malloc(sizeof(type));  
    if (NULL == stack->data)
    {
        perror("malloc stack->data");
        free (stack);
        exit(1);
    }
    stack->data_size = 1;
    stack->top = -1;
    return stack;
}

void pushStack(ST *stack,type val){
    if (NULL == stack)
    {
        puts("NULL stack");
        exit(1);
    }
    if (stack->top == stack->data_size - 1 )
    {
        int new_size = stack->data_size * 2;
        stack->data = (type*)realloc(stack->data,new_size * sizeof(type));
        ERROR_CHECK(NULL,stack->data,"realloc push");
        stack->data_size = new_size;
    }
    
    stack->data[++stack->top] = val;
}  
type popStack(ST *stack){
     if (NULL == stack)
    {
        puts("NULL stack");
        exit(1);
    }
    if (isEmpty(stack))
    {
         if (stack->top <= stack->data_size/2 -1)
    {
        int new_size = stack->data_size /2;
        stack->data = (type*)realloc(stack->data,new_size * sizeof(type));
        ERROR_CHECK(NULL,stack->data,"realloc pop");
        stack->data_size = new_size;
    }
    return stack->data[stack->top--];
    }
    puts("stack empty!");
}
void clearStack(ST *stack){
    stack->top = -1;
    stack->data_size = 1;
}
int isEmpty(ST* stack){
        if (NULL == stack)
    {
        puts("NULL stack");
        exit(1);
    }
    return stack->top == -1 ? 0 : 1;
}